package servlet;

import com.geepi.base.DBUtil;
import com.geepi.base.Util;
import model.BasseInfo;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AddCommentServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("doGet start...");
		request.setCharacterEncoding("UTF-8");
		String content = request.getParameter("content");
		String articleId = request.getParameter("articleId");
		String nick = request.getParameter("nick");
		Date currentTime = new Date();
		String lastTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(currentTime);
		String insertSql = String.format("insert into comment (commentId, content, nick, articleId, lastTime) VALUES ('%s', '%s', '%s', '%s', '%s');",
				Util.obtianRandomInt(), content, nick, articleId, lastTime);
		
		int status = -1;
		String message = "";
		DBUtil dbUtil = new DBUtil();
		boolean isOpen = dbUtil.open();
		if (isOpen == false) {
			status = 102;
			message = "数据库打开失败";
		} else {
			boolean isInsertSuccess = dbUtil.update(insertSql);
			if (isInsertSuccess) {
				status = 0;
				message = "发表评论成功";
			} else {
				status = 100002;
				message = "发表评论失败";
			}
		}

		Map<String, Object> tempParamsMap = new HashMap<String, Object>();
		tempParamsMap.put("status", status);
		tempParamsMap.put("msg", message);
		JSONObject jsonObject = null;
		jsonObject = JSONObject.fromObject(tempParamsMap);

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(jsonObject);
		out.flush(); // 必须有这行，不然页面不会显示
		out.close();
		super.doGet(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
		super.doPost(req, resp);
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	

}
